package com.keymozy.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keymozy.pojo.Staff;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {
    //token携带的数据
    public static final ThreadLocal data = new ThreadLocal();
    public static final ConcurrentHashMap<String,String> ipLogin = new ConcurrentHashMap();
    /**
     * 生成token
     * @param o 对象
     * @return
     */
    public static String getToken(Object o){
        if (o == null){
            throw new NullPointerException("传入对象 不能为空");
        }
        StringBuilder sb = new StringBuilder();
        String t = JSON.toJSONString(o);
        String preT = BaseUtil.encoder(t);
        sb.append(preT);
        String newC = DigestUtils.md5Hex(sb.toString());
        sb.append(".").append(newC);
        return sb.toString();
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verify(String token){
        //判断是否为空
        if ("".equals(token) || token==null)
            return false;
        //验证token数据是否正确
        String[] ts = token.split("\\.");
        if (ts.length!=2)
            return false;
        String preT = DigestUtils.md5Hex(ts[0]);
        if (ts[1].equals(preT))
            return true;

        return false;
    }

    public static Object getObj(String token,Class c){
        //判断是否为空
        if ("".equals(token) || token==null)
            return false;
        String[] ts = token.split("\\.");
        String decoder = BaseUtil.decoder(ts[0]);
        Object o = JSONObject.parseObject(decoder, c);
//        System.out.println("token对象数据："+o);
        return o;
    }
}
